var express = require('express');
var router = express.Router();
var md5 = require("md5")
var jwt = require("jsonwebtoken")

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
//   数据库的名字
  database: 'student_base_info'
})

connection.connect()

/*
  登录接口:
  post
  一个username password
*/ 
router.post('/login', function(req, res, next) {
  const {username, password} = req.body;
  //2.username 和 password 和 数据库中的 数据进行比较  从数据库中找到username的这条数据
//   var sqlStr = "select * from system_users where username='" + username + "'";
  var sqlStr = `select * from system_users where username="${username}"`
  // select * from system_users where username='admin'
  connection.query(sqlStr, function (err, rows, fields) {
    if (err) throw err
    console.log('The solution is: ', rows[0].username, rows[0].password)
    if(username === rows[0].username && md5(password) === rows[0].password) {
        var token = "Bearer " + jwt.sign({
            username
        }, "kuaixiang1991", {
            expiresIn: "72h"
        })
        res.send({
            status: 1,
            msg: '登录成功',
            data: {
                token
            }
        })
        return;
    }

    res.send({
        status: 0,
        msg: "登录失败",
        data: {}
    })
  })
  
});


// 登录成功之后才可以访问的接口，获取学生信息，修改学生信息，删除学生信息，增加学生信息。

// 1. 获取数据接口
router.get("/getStudent", (req, res)=> {
    // 1.从数据库中查找 所有学生的信息
    // 这个语句查询的是全部的数据。
    let {page=1, pageSize=10} = req.query

    const offset = (page - 1) * pageSize
    var sqlStr = `select * from student_base_info limit ${offset}, ${pageSize}`;
    connection.query(sqlStr, function (err, rows, fields) {
        // console.log(rows)
        if(err) throw err;
        if(rows.length > 0) {
            res.send({
                status: 1,
                msg: "获取成功",
                data: {
                    studentList: rows
                }
            })
        }
    })
})

// 2. 添加学生信息接口
router.post("/addStudent", (req, res)=>{
    // 1. 获取到post过来的数据
    const {student_id, student_name, student_age, student_phone} = req.body;
    var sqlStr = `insert into student_base_info(student_id, student_name, student_age, student_phone) values("${student_id}","${student_name}", ${student_age}, "${student_phone}")`
    connection.query(sqlStr, function (err, rows, fields) {
        // console.log(rows)
        if(err) throw err;
        console.log(rows)
        if(rows.insertId) {
            res.send({
                status:1,
                msg: "添加成功",
                data: {
                    id: rows.insertId
                }
            })
        }
    })
})

// 3. 删除学生信息
router.delete("/deleteStudent/:id",(req, res)=> {
    const id = req.params.id;
    var sqlStr = `delete from student_base_info where id=${id}`;
    connection.query(sqlStr, function (err, rows, fields) {
        // console.log(rows)
        if(err) throw err;
        // console.log(rows)
        if(rows.affectedRows === 1) {
            res.send({
                status:1,
                msg: "删除成功"
            })
            return
        }

        res.send({
            status:0,
            msg: "删除失败"
        })
    })
})

module.exports = router;
